package com.hmdp.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.CACHE_SHOPTYPE_KEY;

/**
 * @desc
 * @author: weili23
 * @params
 * @Date: 2024/3/18 14:34
 * @version: 1.0
 */
@Service
@Slf4j
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result queryTypeList() {
        // 1.从Redis中查找商品列表缓存
        List<String> cacheList = stringRedisTemplate.opsForList().range(CACHE_SHOPTYPE_KEY, 0, -1);
        // 2.判断是否存在
        if (cacheList!=null && cacheList.size()>0) {
            // 3.存在返回商铺信息
            //字符串转换为ShopType List<String> -> List<ShopType>
            ArrayList<ShopType> shopTypeList = new ArrayList<>();
            for (String cache : cacheList) {
                ShopType shopType = JSONUtil.toBean(cache, ShopType.class);
                shopTypeList.add(shopType);
            }
            return Result.ok(shopTypeList);
        }
        // 4.不存在，查询数据库
        List<ShopType> shopTypes = query().orderByAsc("sort").list();
        // 5.数据库没列表，返回404
        if (shopTypes == null) {
            return Result.fail("商品列表为空！");
        }
        // 6.数据库有列表数据，写入Redis
        /*stringRedisTemplate.opsForValue().set("cache:shop_type:",Convert.toStr(shopTypes));*/
        for (ShopType shopType : shopTypes) {
            stringRedisTemplate.opsForList().rightPush(CACHE_SHOPTYPE_KEY,JSONUtil.toJsonStr(shopType));
        }
        // 7.返回数据
        return Result.ok(shopTypes);
    }


    public void  copy(){
         /*//设置一个key
        String key = CACHE_SHOPTYPE_KEY;
        //从redis中查询，这里设计存的是list集合
        List<String> stringShopTypeList = stringRedisTemplate.opsForList().range(key,0,-1);
        System.out.println("shopTypeJson = " + stringShopTypeList);
        //redis 中不为空，直接返回
        if (stringShopTypeList != null && stringShopTypeList.size() != 0 ) {
            log.info("redis中shopType数据存在");
            //反序列化redis的数据
            ObjectMapper objectMapper = new ObjectMapper();
            List<ShopType> shopTypeList = stringShopTypeList.stream()
                    .parallel().map(ShopType -> {
                        try {
                            return objectMapper.readValue(ShopType, ShopType.class);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        return null;
                    }).collect(Collectors.toList());
            System.out.println("shopTypeList = " + shopTypeList);
            return Result.ok(shopTypeList);
        }
        //redis中为空，查询数据库
        List<ShopType> DBShopTypeList = query().orderByAsc("sort").list();
        if (DBShopTypeList == null || DBShopTypeList.size() ==0) {
            return Result.fail("未查询到shopType数据");
        }
        log.info("从数据库中查询shopType数据");
        //
        //把数据保存到redis中,序列化为jsonstring
        List<String> stringDataList = DBShopTypeList.stream().parallel()
                        .filter(Objects::nonNull)
                                .map(data->{
                                    try {
                                        return new ObjectMapper().writeValueAsString(data);
                                    }catch (JsonProcessingException e){
                                        throw new RuntimeException(e);
                                    }
                                }).collect(Collectors.toList());
        stringRedisTemplate.opsForList().rightPushAll(key,stringDataList);
        //stringRedisTemplate.expire(key,10, TimeUnit.MINUTES);
        return Result.ok(DBShopTypeList);
    }*/
    }
}
